package org.example.backend.demos.web.handler;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.backend.demos.web.result.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@Component
public class FailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
//        response.setStatus(400);
//        response.setContentType("application/json;charset=utf-8");
//        Map<String, Object> result = new HashMap<>();
//        result.put("message", "登录失败");
//        result.put("redirectUrl", "/main");
//        // 添加响应头
//        response.containsHeader("redirectUrl");
//        response.addHeader("redirectUrl", "/main");
//        response.getWriter().write(JSON.toJSONString(result));


        response.setStatus(400);

        response.setContentType("application/json;charset=utf-8");

        PrintWriter printWriter = response.getWriter();

        String string = exception.getLocalizedMessage();

        Result error = Result.error(string);

        String json = JSON.toJSONString(error);

        printWriter.println(json);
    }
}
